package com.photoeditor.demo.ui.fragement.gallery;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.NetworkOnMainThreadException;
import android.os.SystemClock;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.common.base.log.DLog;
import com.google.firebase.ml.vision.face.FirebaseVisionFace;
import com.lzy.okgo.model.Response;
import com.photoeditor.R;
import com.photoeditor.demo.app.XFragment;
import com.photoeditor.demo.db.DataManager;
import com.photoeditor.demo.db.FaceImgBean;
import com.photoeditor.demo.model.bean.DateBean;
import com.photoeditor.demo.model.bean.SeparatorBean;
import com.photoeditor.demo.model.bean.ThumbnailBean;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.mlkit.ImageFaceDetector;
import com.photoeditor.demo.model.share.ShareImageTools;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.activity.edit.ImagePreviewActivity;
import com.photoeditor.demo.ui.adapter.gallery.ICheckedChangeListener;
import com.photoeditor.demo.ui.adapter.gallery.IFaceDetectListener;
import com.photoeditor.demo.ui.adapter.gallery.IOnFragmentChange;
import com.photoeditor.demo.ui.adapter.gallery.ListGridAdapter;
import com.photoeditor.demo.ui.adapter.share.ShareImageListAdapter;
import com.photoeditor.demo.ui.widget.share.ShareImageItem;
import com.photoeditor.demo.ui.widget.share.ShareImageItem.ShareImageItemData;
import com.photoeditor.demo.util.ArrayUtil;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.IDeleteListener;
import com.photoeditor.demo.util.MediaTypeUtil;
import com.photoeditor.demo.util.PermissionUtil;
import com.photoeditor.demo.util.face.FaceBaseCallback;
import com.photoeditor.demo.util.face.FaceUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

import okhttp3.ResponseBody;

public class FaceGalleryFragment extends XFragment implements ImageFaceDetector.OnImageFaceDetectListener {
    /*
     * 用于存储图片的URL
     */
    private ArrayList<ThumbnailBean> mUris;

    /**
     * 主列表
     */
    private ListView mListView;
//	private ListView mModelListView;

    private ListGridAdapter mAdapter;
//	private ListGridAdapter mModelAdapter;

    private DateBean mNowTime;

    private ProgressDialog mProgressDialog;

    /**
     * 删除时的验证Dialog
     */
    private AlertDialog mDeleteConfirmDialog;

    /**
     * 移入私密箱时的验证Dialog
     */
    private AlertDialog mPrivateConfirmDialog;

    private GalleryActivity mActivity;

    private View mContainerView;

    /**
     * 分享相关
     */
    private View mShade;
    private View mSharePanel;
    private GridView mShareImageView;
    private ShareImageListAdapter mShareImageAdapter;

    //空的时候的界面
    private View mEmptyGalleryView;

    public static final int COL_NUM = 3;

    private IFaceDetectListener mLoadingListener;

    private ArrayList<ThumbnailBean> imageList = new ArrayList<>();
    private ArrayList<ThumbnailBean> faceList = new ArrayList<>();
    private volatile boolean stopDetectFace;

    private Uri loadingUri = null;

    public static boolean fromFaceFragment = false;
    public static boolean takePhotoFinish = true;
    private LottieAnimationView mLoadingView;

    private ImageFaceDetector mImageFaceDetector;
    private int detectIndex = 0;
    private String mEntrance;

    public FaceGalleryFragment(ICheckedChangeListener listener, IOnFragmentChange dataListener, IFaceDetectListener dListener) {
        mActivityListener = listener;
        mDataListener = dataListener;
        mLoadingListener = dListener;
    }

    public FaceGalleryFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (GalleryActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View contanerView = inflater.inflate(R.layout.fragment_gallery, container, false);
        initView(contanerView);
        isCreated = true;
        setNeedRefresh(true);
        loadGridFlowAd();
        if (mDataListener != null) {
            mDataListener.onFragmentCreated(GalleryActivity.TYPE_FRAGMENT_FACE);
        }
        return contanerView;
    }

//	@Override
//	public void startDetect() {
//		mLoadingListener.startDetect();
//	}

//	@Override
//	public void endDetect() {
//		mLoadingListener.endDetect();
//	}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (isAdded()) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
                    mSharePanel.setVisibility(View.GONE);
                    mShade.setVisibility(View.GONE);
                    return true;
                }
                if (mAdapter != null && mAdapter.isCheckStatus()) {
                    mActivity.doCancel(mAdapter);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onNewIntent(Intent intent) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GalleryActivity.REQUEST_CODE_PREVIEW) {
            if (data != null) {
                int refresh = data.getIntExtra(ImagePreviewActivity.NEED_RESFREH, ImagePreviewActivity.REFRESH_NONE);
                if (refresh == ImagePreviewActivity.REFRESH_CURRENT) {
                    setNeedRefresh(true);
                    refreshData();
                } else if (refresh == ImagePreviewActivity.REFRESH_ALL) {
                    setNeedRefresh(true);
                    refreshData();
                    if (mDataListener != null) {
                        mDataListener.onDataChange(GalleryActivity.TYPE_FRAGMENT_OTHER_GALLERY);
                    }
                } else if (refresh == ImagePreviewActivity.REFRESH_CURRENT_AND_OTHER_GALLERY) {
                    setNeedRefresh(true);
                    refreshData();
                    if (mDataListener != null) {
                        mDataListener.onDataChange(GalleryActivity.TYPE_FRAGMENT_OTHER_GALLERY);
                    }
                }
            }
        }
    }

    private void initView(View contanerView) {
        mContainerView = contanerView;
        mListView = (ListView) contanerView.findViewById(R.id.list);
        mShade = contanerView.findViewById(R.id.shade);

        if (getArguments() != null) {
            mEntrance = getArguments().getString("fromWhere");
            if (!TextUtils.equals(mEntrance, "baby_main")) {
                initFaceModelView();
            }
        } else {
            initFaceModelView();
        }
        initPermissionView();
        fromFaceFragment = true;
    }

    //添加Model头
    private void initFaceModelView() {
//		View view = View.inflate(getActivity(), R.layout.face_head, null);
//		mListView.addHeaderView(view);
//		String path1 = saveDrawableImg(R.drawable.img_banner_1);
//		String path2 = saveDrawableImg(R.drawable.img_banner_1);
        Uri uri1;
        Uri uri2;

//		if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
        uri1 = getUriFromDrawableRes(mActivity, R.drawable.ic_img_model_male);
        uri2 = getUriFromDrawableRes(mActivity, R.drawable.ic_img_model_female);
//		}else{//点击跳转需要
//			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//				uri1 = FileUtil.getExternalFileUri(path1);
//				uri2 = FileUtil.getExternalFileUri(path2);
//			} else {
//				uri1 = Uri.fromFile(new File(path1));
//				uri2 = Uri.fromFile(new File(path2));
//			}
//		}

        ArrayList<ThumbnailBean> result = new ArrayList<>();
//		result.add(new ThumbnailBean("model1", System.currentTimeMillis(), false, uri1, 0, MediaTypeUtil.TYPE_PNG));
        result.add(new ThumbnailBean("model2", System.currentTimeMillis(), false, uri2, 0, MediaTypeUtil.TYPE_PNG));
        if (mNowTime == null) {
            mNowTime = new DateBean();
        }
        LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
        ArrayList<Object> datas = mActivity.uniformData(result, map, mNowTime, COL_NUM);
        Object o = datas.get(0);
        if (o instanceof ArrayList) {
//			ArrayList<Object> data = (ArrayList<Object>) o;
        } else if (o instanceof SeparatorBean) {
            ((SeparatorBean) o).setName(mActivity.getResources().getString(R.string.face_gallery_model));
        }
        ListGridAdapter mModelAdapter = new ListGridAdapter(datas, map, COL_NUM, mActivity, mNowTime.getDateTime());
        if (getArguments() != null) {
            mEntrance = getArguments().getString("fromWhere");
            if (!TextUtils.isEmpty(mEntrance)) {
                mModelAdapter.setFromWhere(mEntrance);
            }
        }
//		ListView faceModelView = view.findViewById(R.id.modelList);
        ListView faceModelView = mContainerView.findViewById(R.id.faceModelList);
        faceModelView.setVisibility(View.VISIBLE);
        faceModelView.setAdapter(mModelAdapter);
    }

    private String saveDrawableImg(int id) {
        Resources res = this.getResources();
        BitmapDrawable d = (BitmapDrawable) res.getDrawable(id);
        Bitmap img = d.getBitmap();

//		String fn = id+".png";
//		String path = mActivity.getFilesDir() + File.separator + fn;
        String path = Environment.getExternalStorageDirectory().getPath() + "/DCIM/PhotoEditor/" + id + ".png";
        if (new File(path).exists()) {
            return path;
        }
        try {
            OutputStream os = new FileOutputStream(path);
            img.compress(Bitmap.CompressFormat.PNG, 100, os);
            os.close();
        } catch (Exception e) {
            Log.e("TAG", "", e);
        }
        return path;
    }

    private void initPermissionView() {
        if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            mContainerView.findViewById(R.id.layoutPermission).setVisibility(View.VISIBLE);
            mContainerView.findViewById(R.id.tvRequestPermission).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mActivity.handlePermission();
                }
            });
        } else {
            if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.VISIBLE) {
                mContainerView.findViewById(R.id.layoutPermission).setVisibility(View.GONE);
            }
        }
    }

    private void hidePermissionView() {
        if (!PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.VISIBLE) {
                mContainerView.findViewById(R.id.layoutPermission).setVisibility(View.GONE);
            }
        }
    }

    /**
     * 分享界面初始化
     */
    private void initShareImageView() {
        if (mSharePanel == null) {
            ViewStub vs = (ViewStub) mContainerView.findViewById(R.id.share_iamge_viewstub_id);
            if (vs == null) {
                mSharePanel = mContainerView.findViewById(R.id.share_iamge_layout_id);
            } else {
                mSharePanel = vs.inflate();
            }
            mShareImageView = (GridView) mSharePanel.findViewById(R.id.share_gridview);
            LinearLayout.LayoutParams param = (LinearLayout.LayoutParams) mShareImageView.getLayoutParams();
            param.height = ImageHelper.SCREEN_HEIGHT * 2 / 3 - mActivity.getResources().getDimensionPixelSize(R.dimen.share_textview_height);
            mShareImageView.setLayoutParams(param);
            mShareImageView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    if (arg1 instanceof ShareImageItem) {
                        ShareImageItem flag = (ShareImageItem) arg1;
                        ShareImageItemData siid = flag.getItemData();
                        boolean isInstall = ShareImageTools.getAppIsInstalled(mActivity, siid.getmPkgName());
                        if (isInstall) {
                            boolean result = ShareImageTools.startCommonShareMutilMediaActivity(mActivity,
                                    siid.getmPkgName(), siid.getmActivityName(), getSelectedData(), mActivity.getCheckedImageNum(), mActivity.getCheckedVideoNum());
                            mAdapter.setCheckStatus(false);
                            mSharePanel.setVisibility(View.GONE);
                            mShade.setVisibility(View.GONE);
                            if (!result) {
                                Toast.makeText(mActivity, R.string.not_install, Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(mActivity, R.string.not_install, Toast.LENGTH_SHORT).show();
                        }

                        String activityName = flag.getItemData().getmActivityName();
                    }
                }

            });
            mShade.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mSharePanel.setVisibility(View.GONE);
                    mShade.setVisibility(View.GONE);
                    return true;
                }
            });
        }
        mSharePanel.setVisibility(View.VISIBLE);
        mShade.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化分享的Adapter
     */
    private void initShareImageViewAdapter(int imageNum, int videoNum) {
        if (mShareImageAdapter == null) {
            mShareImageAdapter = new ShareImageListAdapter(mActivity, ShareImageTools.getAllShareMutilMediaTools(mActivity, imageNum, videoNum));
            mShareImageView.setAdapter(mShareImageAdapter);
        } else {
            mShareImageAdapter.setData(ShareImageTools.getAllShareMutilMediaTools(mActivity, imageNum, videoNum));
            mShareImageAdapter.notifyDataSetChanged();
        }
    }

    private ArrayList<Uri> getSelectedData() {
        ArrayList<ThumbnailBean> checkedList = mAdapter.getCheckedList();
        int len = checkedList.size();
        ArrayList<Uri> result = new ArrayList<Uri>(len);
        for (int i = 0; i < len; i++) {
            result.add(checkedList.get(i).getUri());
        }
        return result;
    }

    @Override
    public void setNeedRefresh(boolean flag) {
        isNeedRefresh = flag;
    }

    @Override
    public void refreshData() {
        if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return;
        }
        if ((mAdapter == null || isNeedRefresh) && isCreated) {
            setNeedRefresh(false);
            getGettingDataTask().executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR, null, mActivity.getParams());
        }
    }

    @Override
    public void forceRefreshData() {
        if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return;
        }
        if (mActivity == null) {
            return;
        }
        setNeedRefresh(false);
        getGettingDataTask().executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR, null, mActivity.getParams());
    }

    /**
     * 获取数据的异步任务
     *
     * @return
     */
    public AsyncTask<String, Integer, ArrayList<ThumbnailBean>> getGettingDataTask() {
        AsyncTask<String, Integer, ArrayList<ThumbnailBean>> mGetDataTask = new AsyncTask<String, Integer, ArrayList<ThumbnailBean>>() {

            @Override
            protected ArrayList<ThumbnailBean> doInBackground(String... params) {
                ArrayList<ThumbnailBean> datas = null;
//				int isNeedDeal = Integer.valueOf(params[1]);
//				if(isNeedDeal == 0){//all
////					if (mActivity != null && mActivity.isPickToCollageMode()) {
////						// 拼图显示视频时长最大为30s
////						datas = ImageHelper.getThumbnailBeanFromPath(mActivity, params[0], 30 * 1000);
////					} else {
//						datas = ImageHelper.getThumbnailBeanFromPath(mActivity, params[0]);
////					}
//				} else if(isNeedDeal == 1){//代表Image + gif
//					datas = ImageHelper.getImageThumbnailBeanFromPath(mActivity, params[0]);
//				} else if(isNeedDeal == 2){//代表Video
//					datas = ImageHelper.getVideoThumbnailBeanFromPath(mActivity, params[0]);
//				} else if(isNeedDeal == 3){//代表Image + 动态图片（其实是视频）
//					datas = ImageHelper.getImageAndDynamicThumbnailBeanFromPath(mActivity, params[0]);
//				} else if (isNeedDeal == 4) {// 仅图片不包含gif
//					datas = ImageHelper.getImageThumbnailBeanFromPathExcludeGif(mActivity, params[0]);
                imageList = ImageHelper.getImageThumbnailBeanFromPathExcludeGif(mActivity, params[0]);

                //check one face
//				if(list != null && list.size() > 0){
//					try {
//						String base64 = ImageHelper.bitmapToBase64(ImageHelper.UriToBitmap(list.get(0).getUri(), list.get(0).getDegree(), false));
//						FaceUtil.detectFace(base64, /*okObject*/this, new FaceBaseCallback(){
//							@Override
//							public void onError(Response response) {
//								super.onError(response);
//							}
//
//							@Override
//							public void onSuccess(Response response) {
//								super.onSuccess(response);
//								try {
//									int result = FaceUtil.parseFaceDetect(response.getRawResponse().body().string(), 20);
//									if (result == 0){
//										datas.add(list.get(0));
//									}
//								} catch (IOException e) {
//									e.printStackTrace();
//								}
//							}
//						});
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//				}
//				}
                //
                if (datas == null) {
                    datas = new ArrayList<>();
                }
                if (faceList.size() == 0)
                    addCamera(datas);
                return datas;
            }

            @Override
            protected void onPostExecute(ArrayList<ThumbnailBean> result) {
                if (result == null || result.size() == 0) {//做一个保护
//					Toast.makeText(mActivity, R.string.no_pictures, Toast.LENGTH_SHORT).show();
//					mActivity.finish();
//					if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.GONE)
//					getEmptyGalleryView().setVisibility(View.VISIBLE);
                    return;
                }
                if (mEmptyGalleryView != null) {
                    mEmptyGalleryView.setVisibility(View.GONE);
                }
                mUris = result;
                LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
                if (mNowTime == null) {
                    mNowTime = new DateBean();
                }
                ArrayList<Object> datas = mActivity.uniformData(result, map, mNowTime, COL_NUM);
                if (mAdapter == null) {
                    mAdapter = new ListGridAdapter(datas, map, COL_NUM, mActivity, mNowTime.getDateTime());
                    if (getArguments() != null) {
                        mEntrance = getArguments().getString("fromWhere");
                        if (!TextUtils.isEmpty(mEntrance)) {
                            mAdapter.setFromWhere(mEntrance);
                        }
                    }
                    mAdapter.setOnCheckedChangeListener(mActivityListener);
//					mAdapter.setFromFace(true);
                } else {
                    mAdapter.setData(datas, map, mNowTime.getDateTime());
                }
                if (mListView != null) {
                    mListView.setAdapter(mAdapter);
                    if (imageList.size() > 0) {
                        showFaceImage();
                    }
                }
                hidePermissionView();
            }
        };
        return mGetDataTask;
    }

    private void showFaceImage() {
        Uri cameraUri = getUriFromDrawableRes(getActivity(), R.drawable.icon_camera);
        if (cameraUri != null)
            faceList.add(0, new ThumbnailBean("open_camera", System.currentTimeMillis(), false, cameraUri, 90, MediaTypeUtil.TYPE_JPG));
        if (loadingUri == null)
            loadingUri = getUriFromDrawableRes(getActivity(), R.drawable.bg_beauty_normal_in_white_bg);
        faceList.add(1, new ThumbnailBean("loading", System.currentTimeMillis(), false, loadingUri, 90, MediaTypeUtil.TYPE_JPG));
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				stopDetectFace = false;
//				isCameraTakePhoto();
//				for (int i=0; i<imageList.size(); i++){
//					if (stopDetectFace){
//						break;
//					}
//					if (checkFromDb(imageList.get(i).getPath())){
//						continue;
//					}
////					detectImageFace(i);
//				}
        detectIndex = 0;
        detectFace(detectIndex);
//			}
//		}).start();
    }

    //读出在face页拍照的人脸图
    private boolean isCameraTakePhoto() {
        List<FaceImgBean> beans = DataManager.getInstance().getCameraFaceUriBeans(true);
        if (beans != null && beans.size() > 0) {
            Collections.reverse(beans);
            Log.e("tag", "beans.size(): " + beans.size());
            for (int i = 0; i < beans.size(); i++) {
                if (new File(beans.get(i).getPath()).exists()) {
                    ThumbnailBean thumbnailBean = new ThumbnailBean();
                    thumbnailBean.setChecked(false);
                    thumbnailBean.setDate(beans.get(i).getMDate());
                    thumbnailBean.setDegree(beans.get(i).getMDegree());
                    thumbnailBean.setDuration(beans.get(i).getMDuration());
                    thumbnailBean.setPath(beans.get(i).getPath());
                    thumbnailBean.setSelectCount(beans.get(i).getMSelectCount());
                    thumbnailBean.setType(beans.get(i).getMType());
                    thumbnailBean.setUri(Uri.parse(beans.get(i).getMStringUri()));
                    refreshData(thumbnailBean);
                }
            }
            return true;
        } else {
            return false;
        }
    }

    private boolean checkFromDb(String path) {
        FaceImgBean bean = DataManager.getInstance().getFaceUriBean(path);
        if (bean != null) {
            if (bean.getIsFace()) {
//				Log.e("tag", "path: "+path);
//				refresh(bean.getBean());
                refreshData(new ThumbnailBean(bean.getPath(), bean.getMDate(), bean.getIsChecked(), Uri.parse(bean.getMStringUri()), bean.getMDegree(), bean.getMType()));
            }
            return true;
        }
        return false;
    }

    //list添加一个拍照和loading图标
    private void addCamera(ArrayList<ThumbnailBean> datas) {
        if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
            return;
        Uri cameraUri = getUriFromDrawableRes(getActivity(), R.drawable.icon_camera);
        if (cameraUri != null)
            datas.add(0, new ThumbnailBean("open_camera", System.currentTimeMillis(), false, cameraUri, 90, MediaTypeUtil.TYPE_JPG));
        if (loadingUri == null)
            loadingUri = getUriFromDrawableRes(getActivity(), R.drawable.bg_beauty_normal_in_white_bg);
        datas.add(1, new ThumbnailBean("loading", System.currentTimeMillis(), false, loadingUri, 90, MediaTypeUtil.TYPE_JPG));
    }

    private String getResourcesUri(@DrawableRes int id) {
        Resources resources = getResources();
        String uriPath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                resources.getResourcePackageName(id) + "/" +
                resources.getResourceTypeName(id) + "/" +
                resources.getResourceEntryName(id);
        return uriPath;
    }

    public Uri getUriFromDrawableRes(Context context, int id) {
        if (context == null) return null;
        Resources resources = context.getResources();
        if (resources == null) return null;
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + resources.getResourcePackageName(id) + "/"
                + resources.getResourceTypeName(id) + "/"
                + resources.getResourceEntryName(id);
        return Uri.parse(path);
    }


    public void showDeleteConfirmDialog() {
        if (mDeleteConfirmDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setTitle(R.string.tip);
            builder.setMessage(R.string.gallery_delete_dialog_message);
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mDeleteConfirmDialog.dismiss();
                }
            });
            builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    doDelete();
                    mDeleteConfirmDialog.dismiss();
                }
            });
            mDeleteConfirmDialog = builder.create();
            mDeleteConfirmDialog.setCancelable(true);
            mDeleteConfirmDialog.setCanceledOnTouchOutside(false);
            mDeleteConfirmDialog.show();
        } else {
            mDeleteConfirmDialog.show();
        }
    }

    /**
     * 处理点击delete
     */
    private void doDelete() {
        final ArrayList<ThumbnailBean> checkedList = mAdapter.getCheckedList();
        final int len = checkedList.size();
        if (len != 0) {
            new AsyncTask<Void, Integer, ArrayList<ThumbnailBean>>() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    if (mProgressDialog == null) {
                        mProgressDialog = new ProgressDialog(mActivity, ProgressDialog.THEME_HOLO_LIGHT);
                        mProgressDialog.setCancelable(false);
                        mProgressDialog.setCanceledOnTouchOutside(false);
                        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        mProgressDialog.setMax(checkedList.size());
                        mProgressDialog.setTitle(R.string.doing_delete);
                        mProgressDialog.setProgress(0);
                        mProgressDialog.show();
                    } else {
                        dismissProgressDialog();
                        mProgressDialog.setTitle(R.string.doing_delete);
                        mProgressDialog.setMax(checkedList.size());
                        mProgressDialog.show();
                        mProgressDialog.setProgress(0);
                    }
                }

                @Override
                protected void onProgressUpdate(Integer... values) {
                    mProgressDialog.setProgress(mProgressDialog.getProgress() + values[0].intValue());
                    super.onProgressUpdate(values);
                }

                @Override
                protected ArrayList<ThumbnailBean> doInBackground(Void... params) {
//					int l = checkedList.size();
//					for(int i = 0 ; i < l ; i++){
//						ThumbnailBean thumbnailBean = checkedList.get(i);
//						ImageHelper.deleteMediaByUri(mActivity, thumbnailBean.getUri(), thumbnailBean.getPath());
//						publishProgress(i + 1);
//					}
                    final ArrayList<ThumbnailBean> deleteSuccessList = new ArrayList<ThumbnailBean>();
                    ImageHelper.deleteMedia(mActivity, ArrayUtil.copyArray(checkedList), new IDeleteListener<ThumbnailBean>() {
                        @Override
                        public void onDeleteFile(ThumbnailBean bean, boolean success) {
                            publishProgress(1);
                            if (success) {
                                deleteSuccessList.add(bean);
                            }
                        }

                        @Override
                        public void onDeleteFiles(boolean success) {//在这里不存在这种情况

                        }
                    }, true);
                    return deleteSuccessList;
                }

                @Override
                protected void onPostExecute(ArrayList<ThumbnailBean> result) {
                    dismissProgressDialog();
                    if (result.size() == len) {
                        Toast.makeText(mActivity, R.string.delete_success, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(mActivity, R.string.delete_fail, Toast.LENGTH_SHORT).show();
                    }

                    if (mDataListener != null) {
                        mDataListener.onDataChange(GalleryActivity.TYPE_FRAGMENT_OTHER_GALLERY);
                    }

                    mUris.removeAll(result);
                    if (mUris.size() == 0) {
                        if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.GONE)
                            getEmptyGalleryView().setVisibility(View.VISIBLE);
                    }
                    mAdapter.restoreCheckedList();
                    LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
                    if (mNowTime == null) {
                        mNowTime = new DateBean();
                    }
                    ArrayList<Object> datas = mActivity.uniformData(mUris, map, mNowTime, COL_NUM);
                    mAdapter.setData(datas, map, mNowTime.getDateTime());
                    mAdapter.setCheckStatus(false);
                    super.onPostExecute(result);
                }
            }.executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR);

        }
    }

    public int getPosition(ThumbnailBean bean) {
        return mUris.indexOf(bean);
    }

    @Override
    public void startImagePreviewActivity(ThumbnailBean bean, int requestCode) {
        if (bean != null && mUris != null) {
            Intent i = new Intent(mActivity, ImagePreviewActivity.class);
            i.putExtra(ImagePreviewActivity.ENTRANCE, ImagePreviewActivity.FROM_GALLERY);
            int position = getPosition(bean);
            i.putExtra(ImagePreviewActivity.POSITION, position);
            mActivity.startActivityForResult(i, requestCode);
			/*if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
				ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(mActivity);
				mActivity.startActivityForResult(i, requestCode, transitionActivityOptions.toBundle());
			} else{
				mActivity.startActivityForResult(i, requestCode);
//				mActivity.overridePendingTransition(R.anim.activity_bottom_in, 0);
			}*/
        }
    }

    @Override
    public ListGridAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void doOnStart() {
        if (isAdded()) {
            refreshData();
        }
    }


    @Override
    public void onMoveClick(View v) {
    }

    @Override
    public boolean onBackClick(View v) {
        return false;
    }

    @Override
    public void onCancelClick(View v) {
        if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
            mSharePanel.setVisibility(View.GONE);
            mShade.setVisibility(View.GONE);
        }
        if (mAdapter != null) {
            if (mAdapter.isCheckStatus()) {
                mActivity.doCancel(mAdapter);
            } else {
                mActivity.statisticsBack();
                mActivity.finish();
            }
        } else {
            mActivity.statisticsBack();
            mActivity.finish();
        }
    }

    @Override
    public void onShareClick(View v) {
        initShareImageView();
        initShareImageViewAdapter(mActivity.getCheckedImageNum(), mActivity.getCheckedVideoNum());
    }

    @Override
    public void onDeleteClick(View v) {
        showDeleteConfirmDialog();
    }

    @Override
    public int getImageNum() {
        return mUris.size();
    }

    private View getEmptyGalleryView() {
        if (mEmptyGalleryView == null) {
            ViewStub vs = (ViewStub) mContainerView.findViewById(R.id.empty_gallery_viewstub_id);
            if (vs != null) {
                mEmptyGalleryView = vs.inflate();
            } else {
                mEmptyGalleryView = mContainerView.findViewById(R.id.empty_gallery_layout_id);
            }
            if (mEmptyGalleryView != null) {
                TextView title = (TextView) mEmptyGalleryView.findViewById(R.id.empty_title);
                TextView content = (TextView) mEmptyGalleryView.findViewById(R.id.empty_content);
                View bt = mEmptyGalleryView.findViewById(R.id.empty_bt);
                title.setText(R.string.gallery_empty_title);
                content.setText(R.string.gallery_empty_content);
                bt.setVisibility(View.VISIBLE);
                bt.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        //TODO:调用系统相机
//						Intent intent = new Intent(mActivity, MainActivity.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//								| Intent.FLAG_ACTIVITY_SINGLE_TOP
//								| Intent.FLAG_ACTIVITY_CLEAR_TOP);
//						intent.putExtra(ActionConstant.Extras.EXTRA_PAGE, MainActivity.PAGE_CAMERA);
//						mActivity.startActivity(intent);
                    }
                });
            }
        }
        return mEmptyGalleryView;
    }

    /**
     * 切tab时需要执行
     */
    public void setShareViewGone() {
        if (mShade != null && mShade.getVisibility() == View.VISIBLE) {
            if (mSharePanel != null) {
                mSharePanel.setVisibility(View.GONE);
            }
            if (mShade != null) {
                mShade.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 隐藏进度的Dialog
     */
    private void dismissProgressDialog() {
        try {
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
        } catch (Throwable e) {
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destoryGridFlowAd();
        cancelRequest();
        fromFaceFragment = false;
        detectFinish(-1);
    }

    private void cancelRequest() {
        if (mAdapter != null) {
            mAdapter.cancelCall();
        }
    }


    private void loadGridFlowAd() {

    }

    private void destoryGridFlowAd() {

    }

    public void takePhotoBack(ThumbnailBean thumbnailBean) {
        if (mActivity == null || thumbnailBean == null) {
            return;
        }
        //goto image edit
//		mAdapter.gotoFaceReportActivity(thumbnailBean);
        Log.e("tag", "takePhotoBack uri: " + thumbnailBean.getUri());
        if (mContainerView != null) {
            mLoadingView = mContainerView.findViewById(R.id.loading_animation_view);
            mLoadingView.setVisibility(View.VISIBLE);
            mLoadingView.playAnimation();
        }
//		detectCameraPhotoFace(thumbnailBean);
        if (mAdapter != null) {
            mAdapter.gotoFaceReportActivity(thumbnailBean, true);
        }
//		mActivity.setNeedExitPageAd(false);
    }

    private void detectCameraPhotoFace(final ThumbnailBean thumbnailBean) {
        Bitmap bitmap = ImageHelper.UriToBitmap(thumbnailBean.getUri(), thumbnailBean.getDegree(), false);
        if (bitmap == null) {
            Log.e("tag", "bitmap == null");
            detectFinish(-1);
            return;
        }
        final Bitmap resBmp = ImageHelper.compressJpgToLimitKB(bitmap, 50);
        if (!bitmap.isRecycled()) {
            bitmap.recycle();
        }
        try {
            String base64 = ImageHelper.bitmapToBase64(resBmp);
            if (!resBmp.isRecycled()) {
                resBmp.recycle();
            }
            final long startTime = System.currentTimeMillis();
            FaceUtil.detectFace(base64, /*okObject*/this, new FaceBaseCallback() {
                @Override
                public void onError(Response response) {
                    super.onError(response);
                    detectFinish(-1);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mActivity, mActivity.getResources().getString(R.string.detect_face_error), Toast.LENGTH_SHORT).show();
//							forceRefreshData();
                        }
                    });
                }

                @Override
                public void onSuccess(Response response) {
                    super.onSuccess(response);
//					mFaceDetectListener.endDetect();
                    try {
                        int result = -1;
                        ResponseBody body = response.getRawResponse().body();
                        if (body != null) {
                            result = FaceUtil.parseFaceDetect(body.string(), 20);
                        }

                        if (result == -2) {
                            //解析数据错误
                        } else if (result == -1) {
                            //没有脸
                        } else if (result == 0) {
                            //检测到一张正脸
//							faceList.add(1, thumbnailBean);
                            thumbnailBean.setChecked(true);//标识face页拍照的人脸图
                            saveImgInfo(thumbnailBean, true);
//							updateImgInfo(thumbnailBean);
                            //
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
                                    if (mNowTime == null) {
                                        mNowTime = new DateBean();
                                    }
                                    ArrayList<Object> datas = mActivity.uniformData(faceList, map, mNowTime, COL_NUM);
                                    mAdapter.setData(datas, map, mNowTime.getDateTime());
                                    mAdapter.notifyDataSetChanged();
                                    SystemClock.sleep(300);
                                    mAdapter.gotoFaceReportActivity(thumbnailBean, false);
                                }
                            });
                        } else if (result == 1) {
                            //一张侧脸
//							hasFace[0] = true;
                        } else if (result > 1) {
                            //多张脸
                        }
                        if (result != 0) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(mActivity, mActivity.getResources().getString(R.string.detect_face_error), Toast.LENGTH_SHORT).show();
//									forceRefreshData();
                                }
                            });
                        }
                        detectFinish(result);
                    } catch (IOException e) {
                        e.printStackTrace();
                        detectFinish(-1);
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //
        }
    }


    private void detectFace(final int position) {
        if (stopDetectFace) {
            Log.e("tag", "detectFinish: ");
            return;
        }
        if (checkFromDb(imageList.get(position).getPath())) {
            detectNext();
            return;
        }
        if (mImageFaceDetector == null) {
            mImageFaceDetector = new ImageFaceDetector();
            mImageFaceDetector.setListener(this);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
//				Bitmap bitmap = ImageHelper.UriToBitmap(imageList.get(position).getUri(), imageList.get(position).getDegree(), false);
                Bitmap bitmap = ImageHelper.getBitmapFromPath(imageList.get(position).getPath());
                if (bitmap != null && (bitmap.getWidth() > 10 && bitmap.getHeight() > 10)) {
                    mImageFaceDetector.startDetectLandmark(/*ImageHelper.compressJpgToLimitKB(bitmap, 50)*/bitmap);
//					if (!bitmap.isRecycled()) {
//						bitmap.recycle();
//					}
                } else {
                    detectNext();
                }
            }
        }).start();
    }

    private void detectNext() {
        detectIndex++;
        detectSkipDb();
        if (detectIndex < imageList.size()) {
            detectFace(detectIndex);
        } else {
            imageList.remove(imageList.size() - 1);
            refreshData(null);
        }
    }

    private void detectSkipDb() {
        for (; detectIndex < imageList.size(); detectIndex++) {
            if (!checkFromDb(imageList.get(detectIndex).getPath())) {
                break;
            }
        }
    }

    private void detectFinish(int result) {
        stopDetectFace = true;
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
            mLoadingView.cancelAnimation();
        }
        takePhotoFinish = true;
        if (mImageFaceDetector != null)
            mImageFaceDetector.release();
    }

    //	private boolean isFace;
    private void detectImageFace(final int index) {
//		isFace = false;
        Bitmap bitmap = ImageHelper.UriToBitmap(imageList.get(index).getUri(), imageList.get(index).getDegree(), false);
        if (bitmap == null) return;
        final Bitmap resBmp = ImageHelper.compressJpgToLimitKB(bitmap, 50);
        if (!bitmap.isRecycled()) {
            bitmap.recycle();
        }
        try {
            String base64 = ImageHelper.bitmapToBase64(resBmp);
            if (!resBmp.isRecycled()) {
                resBmp.recycle();
            }
            final long startTime = System.currentTimeMillis();
            FaceUtil.detectFace(base64, /*okObject*/this, new FaceBaseCallback() {
                @Override
                public void onError(Response response) {
                    super.onError(response);
                }

                @Override
                public void onSuccess(Response response) {
                    super.onSuccess(response);
//					mFaceDetectListener.endDetect();
                    try {
                        int result = FaceUtil.parseFaceDetect(response.getRawResponse().body().string(), 20);
                        if (result == -2) {
                            //解析数据错误
                        } else if (result == -1) {
                            //没有脸
                        } else if (result == 0) {
                            //检测到一张正脸
//							faceList.remove(faceList.size()-1);
//							faceList.add(imageList.get(index));
//							Uri loadingUri = getUriFromDrawableRes(getActivity(), R.drawable.bg_beauty_normal_in_white_bg);
//							if (loadingUri != null)
//								faceList.add(faceList.size(), new ThumbnailBean("loading", imageList.get(index).getDate(), false, loadingUri, 90, MediaTypeUtil.TYPE_JPG));
//							runOnUiThread(new Runnable() {
//								@Override
//								public void run() {
//									refresh();
//								}
//							});
//							isFace = true;
                            updateImgInfo(imageList.get(index));
                            refreshData(imageList.get(index));
                        } else if (result == 1) {
                            //一张侧脸
//							hasFace[0] = true;
                        } else if (result > 1) {
                            //多张脸
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (NetworkOnMainThreadException e) {
                        //不应该有此异常，测试有出现
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (index >= imageList.size() - 1) {
                refreshData(null);
            }
            saveImgInfo(imageList.get(index), false);
        }
    }

    //已筛查过的保存到数据库
    private void saveImgInfo(ThumbnailBean thumbnailBean, boolean isFace) {
        FaceImgBean bean = new FaceImgBean();
        bean.setIsFace(isFace);
        bean.setPath(thumbnailBean.getPath());
//			bean.setBean(imageList.get(index));
        bean.setMDate(thumbnailBean.getDate());
        bean.setIsChecked(thumbnailBean.isChecked());
        bean.setMStringUri(thumbnailBean.getUri().toString());
        bean.setMDegree(thumbnailBean.getDegree());
        bean.setMType(thumbnailBean.getType());
        bean.setMDuration(thumbnailBean.getDuration());
        bean.setMSelectCount(thumbnailBean.getSelectCount());
        DataManager.getInstance().insertFaceBean(bean);
    }

    //检测到face，更新数据库
    private void updateImgInfo(ThumbnailBean thumbnailBean) {
        FaceImgBean faceImgBean = DataManager.getInstance().getFaceUriBean(thumbnailBean.getPath());
        if (faceImgBean != null) {
            faceImgBean.setIsFace(true);
            DataManager.getInstance().updateFaceUriBean(faceImgBean);
        }
    }

    private volatile boolean refreshing = false;

    private void refreshData(ThumbnailBean bean) {
        if (refreshing) {
            return;
        }
        if (bean != null) {
            faceList.remove(faceList.size() - 1);//remove loading img
            faceList.add(bean);
            if (loadingUri == null)
                loadingUri = getUriFromDrawableRes(getActivity(), R.drawable.bg_beauty_normal_in_white_bg);
            faceList.add(faceList.size(), new ThumbnailBean("loading", bean.getDate(), false, loadingUri, 90, MediaTypeUtil.TYPE_JPG));//add loading img to last
        } else {
            if (faceList.size() > 0) {
                faceList.remove(faceList.size() - 1);
            }
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
                if (mNowTime == null) {
                    mNowTime = new DateBean();
                }
                ArrayList<Object> datas = mActivity.uniformData(faceList, map, mNowTime, COL_NUM);
                mAdapter.setData(datas, map, mNowTime.getDateTime());
                mAdapter.notifyDataSetChanged();
                refreshing = false;
            }
        });
    }


    @Override
    public void onDetectFaceSuccess(@NonNull List<FirebaseVisionFace> results) {
        DLog.d("gvLog", "success1");
    }

    @Override
    public void onDetectFaceFailure(@NonNull Exception e) {
        DLog.d("gvLog", "fail1");
    }

    @Override
    public void onDetectFaceLandmarkSuccess(@NonNull List<FirebaseVisionFace> results) {
        DLog.d("gvLog", "results: " + results.size());
        saveImgInfo(imageList.get(detectIndex), (results != null && results.size() == 1));
        if (results != null && results.size() == 1) {
            refreshData(imageList.get(detectIndex));
        }
        detectNext();
    }

    @Override
    public void onDetectFaceLandmarkFailure(@NonNull Exception e) {
        DLog.d("gvLog", "fail");
        detectNext();
    }

}
